import { Component, OnInit ,OnDestroy} from '@angular/core';
import { Router ,RouteParams} from '@angular/router-deprecated';
import { Param } from '../model/param.model';
import { Api } from '../model/api.model';
import { Proj } from '../model/proj.model';
import { Group } from '../model/group.model';
import {BaseRequestOptions,Http,Response, HTTP_PROVIDERS,Headers} from '@angular/http';
import { GlobalService } from '../services/global.service';
import { ApiService } from '../services/api.service';
import { GroupService } from '../services/group.service';

@Component({
  selector: 'api-component',
  viewProviders: [HTTP_PROVIDERS,ApiService,GroupService],
  templateUrl: 'app/api/tpl/apis.tpl.html'
})
export class ApisComponent implements OnInit,OnDestroy {
  apis:Api[] = [];
  group:Group = new Group();
  proj:Proj = new Proj();
  allGroups:Group[] = [];
  allDocsByProject:any = {};
  deleteApiId:string;
  deleteApiIndex:number;
  constructor(private router: Router,routeParams:RouteParams,private apiService:ApiService,private groupService:GroupService) {

    this.apiService.authInit(router,()=>{
      let groupId:string = routeParams.get("groupId");
      let projId:string = routeParams.get("projId");
      this.proj._id = projId;
      this.group._id = groupId;
      if(this.apiService.getApisByProj(this.proj._id))
      this.apiService.getApisByProj(this.proj._id).subscribe(data=>{
        this.allDocsByProject = data.json();
        if(this.allDocsByProject.groups && this.allDocsByProject.groups.length>0)
        for(var i=0;i<this.allDocsByProject.groups.length;i++)
        {
          var g = this.allDocsByProject.groups[i];
          console.log(g)
          if(g._id == groupId)
          {
            this.apis = g.docs;
            console.log(this.apis)
          }
        }
      });
    });
  }

  ngOnInit() {

  }

  ngOnDestroy(){

  }

  addApi()
  {
    this.router.navigate(['AddApi',{projId:this.proj._id}]);
  }

  editApi(apiId,index)
  {
    this.router.navigate(['EditApi',{apiId:apiId,groupId:this.group._id,projId:this.proj._id}]);
  }

  deleteApi(apiId,i)
  {
    $('.ui.basic.modal')['modal']('show');
    this.deleteApiId = apiId;
    this.deleteApiIndex = i;
  }

  showApi(apiId,index)
  {
    this.router.navigate(['ShowApi',{apiId:apiId}]);
  }

  showApis(groupId)
  {
    this.router.navigate(['Apis',{groupId:groupId,projId:this.proj._id}]);
  }

  cancelDelete()
  {
    $('.ui.basic.modal')['modal']('hide');
  }

  confirmDelete()
  {
    this.apiService.deleteApi(this.deleteApiId).subscribe(()=>{
      $('.ui.basic.modal')['modal']('hide');
      this.apis.splice(this.deleteApiIndex,1);
    });
  }
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
